<template>
  <el-cascader
    v-model="inputValue"
    class="w-full"
    :options="dataOptions"
    :props="defaultProps"
    size="small"
    :placeholder="placeholder"
    :clearable="clearable"
  ></el-cascader>
</template>

<script>
import { systemDepartmentList } from "@/api/department";
import { convertToTree } from "@/util";

export default {
  name: "DepartmentTree",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    /**
     * 禁用状态
     */
    disabled: {
      type: Boolean,
      default: false,
    },
    /**
     * 占位符
     */
    placeholder: {
      type: String,
      default: "所属部门",
    },
    /**
     * 是否支持清空选项
     */
    clearable: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      defaultProps: {
        expandTrigger: "hover",
        label: "name",
        value: "id",
        checkStrictly: true,
      },
      // 选择器数据源
      dataOptions: [],
      departmentList: [],
    };
  },
  computed: {
    // 选中值
    inputValue: {
      get() {
        return this.value;
      },
      set(val) {
        const _id = Array.isArray(val) ? val[val.length - 1] : val;
        const item = this.departmentList.find((v) => {
          return v.id === _id;
        });
        this.$emit("change", _id, item);
      },
    },
  },
  created() {
    this.getDepartmentList();
  },
  activated() {
    this.getDepartmentList();
  },
  methods: {
    async getDepartmentList() {
      const { content } = await systemDepartmentList({ pageIndex: 1, length: 999 });
      this.departmentList = content;
      content.map((item) => (item.parentId ? "" : (item.parentId = null)));
      this.dataOptions = convertToTree(content);
    },
  },
};
</script>

<style lang="scss" scoped></style>
